const Koa = require('koa');
const app = new Koa();

const KoaRouter = require('koa-router');
const router = new KoaRouter();

const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

const { query } = require('./util/index.js');

router.post('/register', async (ctx) => {
    // 获取参数
    const { username, password, nickname } = ctx.request.body;
    // 非空校验
    if (!username || !password || !nickname) {
        ctx.body = {
            code: 400,
            message: '缺少必须参数',
        };
        return;
    }
    // 用户唯一性校验
    let res = await query('select * from user where username = ?', [username]);
    // 判断是不是已经存在该用户了
    if (res.length > 0) {
        ctx.body = {
            code: 403,
            message: '该用户已存在，不允许重复创建',
        };
        return;
    }
    // 保存到数据库中
    res = await query(
        'insert into user (username, password, nickname) values (?, ?, ?)',
        [username, password, nickname],
    );
    // 判断是否添加成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: '用户添加失败，请稍后再试',
        };
        return;
    }
    // 添加成功
    ctx.body = {
        code: 201,
        message: '用户添加成功',
    };
});

router.post('/login', async (ctx) => {
    // 获取参数
    const { username, password } = ctx.request.body;
    // 用户是否存在
    let res = await query('select * from user where username = ?', [username]);
    if (res.length === 0) {
        ctx.body = {
            code: 404,
            message: '该用户未注册，请先注册',
        };
        return;
    }
    // 存在，拿到用户
    const user = res[0];
    // 判断密码是否可注册时，填写的一样
    if (user.password !== password) {
        ctx.body = {
            code: 400,
            message: '用户密码错误',
        };
        return;
    }
    // 密码不能给前端看
    delete user.password;
    // 登录成功
    ctx.body = {
        code: 200,
        data: user,
        message: '登录成功',
    };
});

router.post('/blogs', async (ctx) => {
    // 获取参数
    const { title, content } = ctx.request.body;
    // 非空校验
    if (!title || !content) {
        ctx.body = {
            code: 400,
            message: '缺少必需参数',
        };
        return;
    }
    // 添加到数据库
    const res = await query(
        'insert into blog (title, content, uid, create_time) values (?, ?, ?, ?)',
        [title, content, uid, new Date()],
    );
    // 判断是否插入成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: '博客发表失败，请稍后再试！',
        };
        return;
    }
    // 返回添加成功响应
    ctx.body = {
        code: 201,
        message: '博客发表成功',
    };
});

router.get('/blogs', async (ctx) => {
    let sql = `
            select b.id, b.title, b.content, b.create_time, u.nickname 
            from blog as b 
            join user as u on b.uid = u.id
        `;
    const res = await query(sql);
    ctx.body = {
        code: 200,
        data: res,
        message: '获取博客列表成功',
    };
});

app.use(router.routes());

// 监听端口，提供服务
app.listen(3000, () => {
    console.log('Koa server listening at http://localhost:3000');
});
